/*
 *  BoostGestureClassifier.cpp
 *  
 *
 *  Created by Rasmus Kyng on 14/02/2011.
 *  Copyright 2011 __MyCompanyName__. All rights reserved.
 *
 */
#include "HandInterface.hpp"
using namespace hi;
using namespace cv;

BoostGestureClassifier::BoostGestureClassifier(  const char* mlName, string pcaName, cv::Ptr< AbstractProbabilityTransformer > probTransPtr )
: MLGestureClassifier( pcaName, probTransPtr ) {
	boost = CvBoost();
	char* boostFileName_orphan = strAppend_orphanOut( mlName, ".boost.xml" ); //TODO handle via resource tracker
	
	CvFileStorage* fsPtr = cvOpenFileStorage(
											 boostFileName_orphan,
											 0,
											 CV_STORAGE_READ
											 );
	
	CvFileNode* nodePtr = cvGetFileNodeByName( fsPtr, NULL, mlName ); //CHECK!
	
	boost.read( fsPtr, nodePtr );
	
	cvReleaseFileStorage( &fsPtr );
	
	delete boostFileName_orphan;
}

bool BoostGestureClassifier::predict( cv::Mat& dataSampleForPrediction ) {
	
	missingMask.create( dataSampleForPrediction.size(), CV_8UC1 );
	//CvBoost should be able to work without this missing mask, but a bug in OpenCV means it's currently necessary!
	//NOTE: buffer reuse gives slight speed improvement
	
	float gesturePrediction = boost.predict( dataSampleForPrediction, missingMask );
	
	bool predictedActive;
	
	if ( gesturePrediction == 0.0) {
		predictedActive = true;
		//circle(imgToDraw, Point(20, 5), 4, Scalar(0, 0, 255), 2); //FIX add existence check!
	} else if ( gesturePrediction == 1.0) {
		predictedActive = false;
		//circle(imgToDraw, Point(20, 5), 2, Scalar(0, 255, 0), 2);
	} else {
		CV_Error( CV_StsError, "Unexpected prediction!"); //throws exception!
	}
	
	return predictedActive;
}